/***************************************************************************
 *   Copyright (C) 2009 by Docteur Pierre-Marie Desombre.   *
 *   pm.desombre@medsyn.fr  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 3 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "preview.h"
#include "constants.h"

#include <QDir>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QTextDocument>
#include <QDateTime>
#include <QSettings>
#include <QDebug>

Preview::Preview(QWidget * parent)
{
    setupUi(this);
    m_resources = qApp->applicationDirPath()+"/../resources";
    QString apituxini = m_resources+"/apitux.ini";
    QSettings setting(apituxini,QSettings::IniFormat);
    m_police = setting.value("police/type").toString();
    m_codec = setting.value("codec/type").toString();
    setCombo();
    qDebug() << __FILE__ << QString::number(__LINE__) << " file =" << comboBox->currentText() ;
    displayFile(comboBox->currentText());
    connect(quitButton,SIGNAL(pressed()),this,SLOT(close()));
    connect(comboBox,SIGNAL(highlighted(const QString&)),this,SLOT(displayFile(const QString&)));
    connect(applyButton,SIGNAL(pressed()),this,SLOT(modifytext()));
    connect(deleteButton,SIGNAL(pressed()),this,SLOT(deletefile()));
    connect(resolvButton,SIGNAL(pressed()),this,SLOT(savefortreatment()));    
}

Preview::~Preview(){}

void Preview::displayFile(const QString & fileName)
{
    QStringList textlist;
    QString text;
    QByteArray codecarray = m_codec.toLatin1();
    const char * codecchar = codecarray.data();
    QFile file(m_resources+QDir::separator()+"apitemp"+QDir::separator()+fileName);
    if (!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open file : " << fileName ;
        }
    QTextStream stream(&file);
    stream.setCodec(codecchar);
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        if (!line.contains("TEX|")&&!line.contains("RES|"))
         {
               textlist << line;
               }
        }
    text = textlist.join("\n");
    QTextDocument *doc = new QTextDocument;
    doc->setPlainText(text);
    textEdit->setDocument(doc);
}

void Preview::setCombo()
{
    if (comboBox->count()>0)
    {
          comboBox->clear();
        }
    QDir dir(m_resources+"/apitemp");
    if (!dir.exists())
    {
          QMessageBox::warning(0,trUtf8("Erreur"),m_resources+"/apitemp"+trUtf8("n'existe pas.'"),QMessageBox::Ok);
        }
    dir.setFilter(QDir::Files);
    QStringList fileslist;
    fileslist = dir.entryList();
    int i = 0;
    foreach(QString file,fileslist){
        QString simplifiedNameFile = file;
        if (file.contains(QDir::separator()))
        {
              simplifiedNameFile = file.split(QDir::separator()).last();
            }
         m_hashIntFiles.insert(i,simplifiedNameFile);
        comboBox->addItem(simplifiedNameFile);//TODO classer items
        }
}

void Preview::modifytext(){
  QString texte;
  texte = textEdit->toPlainText();
  QString fileName = comboBox->currentText();
  QString resutext = m_resources+QDir::separator()+"apitemp"+QDir::separator()+fileName;
  QFile file(resutext);
  if(!file.open(QIODevice::ReadWrite|QIODevice::Text)){
	QMessageBox::warning(0,tr("erreur"),trUtf8("resutext ne peut pas être ouvert !"),QMessageBox::Ok);
	}
  QTextStream tamise(&file);
  const char*codec = "ISO 8859-1";
  tamise.setCodec(codec);
  tamise << texte;
  file.close();
}

void Preview::deletefile()
{
    QString filename = comboBox->currentText();
    QString filenewname;
    QFile file(m_resources+QDir::separator()+"apitemp"+QDir::separator()+filename);
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << filename+" cannot open" ;
        }
    QString name;
    QString firstname;
    QStringList listoflines;
    QTextStream s(&file);
    while (!s.atEnd())
    {
        listoflines << s.readLine();
        }
    if (listoflines.size()>PRENOM)
    {
          name = listoflines[NOM];
          firstname = listoflines[PRENOM];
        }
    QDateTime dateTime = QDateTime::currentDateTime();
    filenewname = name+"_"+firstname+"_"+dateTime.toString("yyyy-MM-dd-hh-mm-ss")+"_"+filename;
    if (!file.copy(m_resources+QDir::separator()+"apitempSauve"+QDir::separator()+filenewname))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to copy file to : " << filenewname;
        }
    file.close();
    if (file.remove())
    {
          QMessageBox::information(0,trUtf8("Info"),
          trUtf8("Le fichier a été effacé\nmais copié dans apitempSauve : ")+filename,QMessageBox::Ok);
          setCombo();
          displayFile(comboBox->currentText());
        }
}

void Preview::savefortreatment()
{
    QString filename = comboBox->currentText();
    QString filenewname;
    QFile file(m_resources+QDir::separator()+"apitemp"+QDir::separator()+filename);
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << filename+" cannot open" ;
        }
    QString name;
    QString firstname;
    QStringList listoflines;
    QTextStream s(&file);
    while (!s.atEnd())
    {
        listoflines << s.readLine();
        }
    if (listoflines.size()>PRENOM)
    {
          name = listoflines[NOM];
          firstname = listoflines[PRENOM];
        }
    QDateTime dateTime = QDateTime::currentDateTime();
    filenewname = name+"_"+firstname+"_"+dateTime.toString("yyyy-MM-dd-hh-mm-ss")+"_"+filename;
    if (file.copy(m_resources+QDir::separator()+"dossiers_a_traiter"+QDir::separator()+filenewname))
    {
          QMessageBox::information(0,trUtf8("Info"),
          trUtf8("Le dossier a été placé dans les dossiers à traiter : ")+filename,QMessageBox::Ok);
        }
}
